package org.robot.scm.platform.server.common;

import com.google.common.collect.Lists;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.pojos.platform.LoggerInfo;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.StreamUtils;

@Slf4j
public class LoggerHelper {

    public static String getLogger(String key) {
        List<String> logList = LocalCacheHelper.getList(key);
        if (CollectionUtils.isEmpty(logList)) {
            return StringUtils.EMPTY;
        }
        CopyOnWriteArrayList<String> strings = new CopyOnWriteArrayList<>(logList);
        if (CollectionUtils.isNotEmpty(strings)) {
            // 所有日志按照时间的倒叙
            List<LoggerInfo> loggerList = toLogger(strings);
            loggerList.sort((o1, o2) -> o2.getTimestamp().compareTo(o1.getTimestamp()));

            List<LoggerInfo> startLoggers = StreamUtils.filter(loggerList, e -> StringUtils.equals(e.getLogName(), "main-thread-start"));
            List<LoggerInfo> endLoggers = StreamUtils.filter(loggerList, e -> StringUtils.equals(e.getLogName(), "main-thread-end"));

            // 找出非main thread的日志，即环境日志, 按照时间倒叙
            List<LoggerInfo> envLoggers = StreamUtils.filter(loggerList, e -> !StringUtils.equals(e.getLogName(), "main-thread-start") && !StringUtils.equals(e.getLogName(), "main-thread-end"));
            Map<String, List<LoggerInfo>> groupBy = StreamUtils.groupBy(envLoggers, LoggerInfo::getLogName);
            groupBy.forEach((k, v) -> v.sort((o1, o2) -> o2.getTimestamp().compareTo(o1.getTimestamp())));

            // 按照时间顺序将日志重组
            StringBuilder builder = new StringBuilder();

            // 结束日志在前面
            for (LoggerInfo log : endLoggers) {
                builder.append(log.getContent()).append("\n");
            }

            // 环境日志,按照环境、时间倒叙插入
            List<String> logKeys = Lists.newArrayList(groupBy.keySet());
            logKeys.sort(Comparator.reverseOrder());
            for (String logKey : logKeys) {
                List<LoggerInfo> loggerInfos = groupBy.get(logKey);
                List<LoggerInfo> newLogger = Lists.newArrayList();
                // 如果日志数量大于70，取前后30条
                if (loggerInfos.size() > 70) {
                    String dateTime = DateTool.format(new Date(), DateTool.PATTERN_8);
                    newLogger.addAll(loggerInfos.subList(0, 30));
                    newLogger.add(LoggerInfo.builder().content(dateTime + " [ 省略 ]").build());
                    newLogger.addAll(loggerInfos.subList(loggerInfos.size() - 30, loggerInfos.size()));
                }else {
                    newLogger.addAll(loggerInfos);
                }
                for (LoggerInfo log : newLogger) {
                    builder.append(log.getContent()).append("\n");
                }
            }

            // 开始日志在后面
            for (LoggerInfo log : startLoggers) {
                builder.append(log.getContent()).append("\n");
            }

            return builder.toString();
        }
        return StringUtils.EMPTY;
    }

    private static List<LoggerInfo> toLogger(CopyOnWriteArrayList<String> strings) {
        return StreamUtils.convert(strings, e -> JsonHelper.toObject(e, LoggerInfo.class));
    }

}
